<?php
/**
 * 通知事件处理
 * @version 2015092911
 * @author Justin <justin@jipu.com>
 */

namespace Home\Event;

class StoreCashEvent{
   
  /**
   * 订单支付后的资金流水 
   * sdp_dis三级分销，consume用户消费,sdp_order分销店铺、refund用户退款，store_cost店铺促销活动费用
   */
  function orderPaid($order_sn , $type = 1 ,$store_id = null){
    if(!$order_sn)return false;
    $map['order_sn'] = $order_sn;
    if($type == 2 && $store_id)$map['store_ids'] = array('in' , $store_id );
    $order    = M('Store_order')->where($map)->select();
    $order_id = M('Order')->where('order_sn ='.$order_sn)->getField('id');
    if($order && $order_id){
      foreach($order as $k => $v){
        $remark  = '订单号:'.$order_sn.'订单收款';
        $flow    = 'in';
        if($type == 2){
          $remark  = '订单号:'.$order_sn.'订单退款';
          $flow    = 'out';
        }
        $sc_data = array();
        $trade_type = (!empty($v['payment_type'])) ? $v['payment_type'] : 'web';
        $sc_data    = array(
          'uid'     =>  $v['uid'],
          'store_id'=>  $v['store_ids'],
          'order_id'=>  $order_id,
          'trade_sn'=>  $v['payment_id'],
          'type'    =>  'consume',
          'trade_type'=>$trade_type,
          'flow'    =>  $flow,
          'amount'  =>  $v['total_amount'],
          'ctime'   =>  $v['update_time'],
          'remark'  =>  $remark,
          'status'  =>  1
        );
        M('StoreCash')->add($sc_data);
        //$sc_data['amount'] = 0;
        $sc_data['flow']   = $type == 2 ?'in' : 'out';
        $remarks = $type == 2 ?'退款，佣金扣除返还' : '佣金扣除';
        $sc_data['remark'] = '订单号:'.$order_sn.$remarks;
        $rate=M('Store')->where('store_id = '.$v['store_ids'])->getField('rate');
        //佣金返还扣除
        if ($type == 2) {
          $maps = array('uid'=>$v['uid'],'store_id'=>$v['store_ids'],'order_id'=>$order_id,'type'=>'consume','flow'=>'out');
          $sc_data['amount'] = M('StoreCash')->where($maps)->getField('amount');
        }else{
          $sc_data['amount'] = ($v['total_price'])*$rate/100;
          $sc_data['amount'] = sprintf('%.2f',$sc_data['amount']);
        }
        if($sc_data['amount'] > 0 )M('StoreCash')->add($sc_data);
      }
    }
      
  }
  /**
   * 分销店铺的商户流水
   */ 
  public function distribute($order_id , $type = 1 , $store_id = null){
    if(!$order_id || !C('DIS_START'))return false;
    $orders = M('Order')->where('id ='.$order_id)->field('order_sn,uid')->find();
    $order_sn = $orders['order_sn'] ; $uid = $orders['uid'];
    if($type == 2 && $store_id)$map['store_ids'] = array('in' , $store_id );
    $map['order_sn'] = $order_sn ;
    $order    = M('Store_order')->where($map)->select();
    if($order && $order_id){
      $people = M('Distribution')->where('user_id='.$uid)->find();
      if($people['oneagents'] > 0 ){
        $right['one'] = M('User')->alias('a')->join('__UNION__ b on a.id=b.uid')->where('a.status =1 and b.status=1 and a.form_union_status=1 and a.id='.$people['oneagents'])->getField('a.id');
      }
      if($people['twoagents'] > 0 && C('DIS_CLASS') > 1 ){
        $right['two'] = M('User')->alias('a')->join('__UNION__ b on a.id=b.uid')->where('a.status =1 and b.status=1 and a.form_union_status=1 and a.id='.$people['twoagents'])->getField('a.id');
      }
      if($people['threeagents'] > 0 && C('DIS_CLASS') > 2 ){
        $right['three'] = M('User')->alias('a')->join('__UNION__ b on a.id=b.uid')->where('a.status =1 and b.status=1 and a.form_union_status=1 and a.id='.$people['threeagents'])->getField('a.id');
      }
      if(!$right['one'])return false;
      $remark = $type == 2 ?  '订单:'.$order_sn.'退款，推广联盟返现扣除返还' : '订单:'.$order_sn.'推广联盟返现扣除';
      $flow = $type == 2 ? 'in' : 'out' ; 
      if($type == 1){
        //返现扣除
        foreach($order as $k => $v){
          $sc_data = array();
          $trade_type = (!empty($v['payment_type'])) ? $v['payment_type'] : 'web';
          $sc_data    = array(
            'uid'     =>  $v['uid'],
            'store_id'=>  $v['store_ids'],
            'order_id'=>  $order_id,
            'trade_sn'=>  $v['payment_id'],
            'type'    =>  'sdp_dis',
            'trade_type'=>$trade_type,
            'flow'    =>  $flow,
            'ctime'   =>  $v['update_time'],
            'remark'  =>  $remark,
            'status'  =>  1
          );
          $item = explode(',' , $v['item_ids']);
          $sc_data['amount'] = 0 ;
          foreach($item as $kk => $vv){
            $item_info = M('Item')->where('id ='.$vv)->field('sdp1,sdp2,sdp3')->find();
            $sdp1 = ($item_info['sdp1'] == '' ||is_null($item_info['sdp1'])) ?　C('FIRISTNAME') : $item_info['sdp1'] ;
            $sdp2 = ($item_info['sdp2'] == '' ||is_null($item_info['sdp2'])) ?　C('SECONDNAME') : $item_info['sdp2'] ;
            $sdp3 = ($item_info['sdp3'] == '' ||is_null($item_info['sdp3'])) ?　C('THIRDNAME') : $item_info['sdp3'] ;
            $ois = M('OrderItem')->where('order_id='.$order_id.' and item_id ='.$vv)->field('quantity,price')->find();
            if($right['two']==0)$sdp2=0;
            if($right['three']==0)$sdp3=0;
            $sdp = $sdp1 + $sdp2 + $sdp3;
            $last = $ois['price']*$ois['quantity'] * $sdp/100;
            $sc_data['amount'] += sprintf( '%.4f' ,$last);
          }
          if($sc_data['amount'] > 0 ) $sc_data['amount'] = sprintf('%.2f',$sc_data['amount']); M('StoreCash')->add($sc_data);
        }
      }else{
        //返现扣除返还
        $maps=array('order_id'=>$order_id,'flow'=>'out','type'=>'sdp_dis','store_id'=>$store_id);
        $store_cash = M('StoreCash')->where($maps)->find();
        if ($store_cash) {
          $sc_data    = array(
            'uid'     =>  $store_cash['uid'],
            'store_id'=>  $store_cash['store_id'],
            'order_id'=>  $order_id,
            'trade_sn'=>  $store_cash['trade_sn'],
            'type'    =>  'sdp_dis',
            'trade_type'=>$store_cash['trade_type'],
            'flow'    =>  $flow,
            'ctime'   =>  NOW_TIME,
            'remark'  =>  $remark,
            'status'  =>  1,
            'amount'  =>  $store_cash['amount']
          );
          M('StoreCash')->add($sc_data);
        }
      }
      
    }
  }
  /**
   * 商户的 分销店铺流水 
   */
  public function sdpOrder($order_id , $type = 1 ,$store_id = null){
    if(!$order_id)return false;
    if($type == 2 && $store_id)$map['so.store_ids'] = array('in' , $store_id );
    $map['o.id'] = $order_id;
    $orders   = M('Store_order')->alias('so')->join('LEFT JOIN __ORDER__ o on o.order_sn = so.order_sn')->where($map)->field('so.*')->select();
    if($orders){
      foreach($orders as $k => $v){
        $items = explode(',' , $v['item_ids']) ;
        $sdp   = 0 ;
        if($type == 1){//分销返现扣除
            foreach($items as $kk => $vv){
              $temp = M('OrderItem')->where('order_id ='.$order_id .' and item_id='.$vv)->field('price ,quantity,sdp_code')->find();
              $count = $this->getCashBackAmount2($vv , $temp['price'] , $temp['quantity']);
              if($temp['sdp_code'] && $count )$sdp += $count;
            }
        }else{//分销返现扣除返还
            $maps = array('order_id'=>$order_id,'type'=>'sdp_order','flow'=>'out','store_id'=>$store_id);
            $store_cash = M('store_cash')->where($maps)->find();
            if($store_cash)$sdp=$store_cash['amount'];
        }
        if($sdp){
          $remark = $type == 2 ? '订单:'.$v['order_sn'].'退款，店铺分销返现扣除返还' : '订单:'.$v['order_sn'].'店铺分销返现扣除';
          $flow = $type == 2 ? 'in' : 'out' ;
          $trade_type = (!empty($v['payment_type'])) ? $v['payment_type'] : 'web';
          $sc_data    = array(
            'uid'     =>  $v['uid'],
            'store_id'=>  $v['store_ids'],
            'order_id'=>  $order_id,
            'trade_sn'=>  $v['payment_id'],
            'type'    =>  'sdp_order',
            'trade_type'=>$trade_type,
            'flow'    =>  $flow,
            'ctime'   =>  $v['update_time'],
            'remark'  =>  $remark,
            'status'  =>  1 ,
            'amount'  => $sdp
          );
          M('StoreCash')->add($sc_data);
        }
      }
    }
  }

  /**
   * 计算返现金额
   * @param int $item_id 商品id
   * @param double $item_price 商品价格
   * @param int $quantity 商品购买数量
   * @version 2015080612
   * @author Justin <justin@jipu.com>
   */
  function getCashBackAmount2($item_id, $item_price, $quantity){
    $data = M('Item')->field('sdp_type, sdp')->find($item_id);
    if(1 == $data['sdp_type']){
      //比例
      $cashback_amount = $item_price * $data['sdp'] / 100;
    }else{
      $cashback_amount = $data['sdp'];
    }
    return ($cashback_amount > $item_price ? $item_price : $cashback_amount) * $quantity;
  }
  
}
